package com.jic.manager.controller.manage.sys;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.manager.common.util.BeanUtil;
import com.jic.manager.entity.SysUser;
import com.jic.manager.request.SysUserRequest;
import com.jic.manager.response.SysUserResponse;
import com.jic.manager.service.SysDeptService;
import com.jic.manager.service.SysUserLoginService;
import com.jic.manager.service.SysUserService;
import com.jic.manager.utils.GraphicHelper;
import com.jic.manager.utils.MD5Utils;
import com.jic.manager.utils.StatusConstant;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("sysLogin")
public class SysLoginController {

    @Resource
    public RedisClientTemplate redisClientTemplate;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private SysUserLoginService sysUserLoginService;

    @ResponseBody
    @RequestMapping(value = "/getVtoken")
    public RestResult<String> getVtoken() {
        try {
           return RestResult.success(UuidUtil.getTimeBasedUuid().toString());
        } catch (Exception e) {
            log.error("获取vtoken错误================>>>>>>>{}",e.getLocalizedMessage());
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getLoginCode")
    public void createAuthCode(@RequestParam String vtoken , HttpServletResponse response) {
        try {
            String verifyCode = GraphicHelper.createImge(130, 36, "png",response.getOutputStream());
            // 图片验证码存放到缓存60秒
            redisClientTemplate.del(vtoken + "_IMAGE_CODE");
            redisClientTemplate.setex(vtoken + "_IMAGE_CODE",Integer.valueOf(StatusConstant.VERIFICATION_TIME.toString()),verifyCode);
        } catch (Exception e) {
            System.err.println(e.getLocalizedMessage());
            e.printStackTrace();
        }
    }

    /**
     * 登录
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/logins",method = RequestMethod.POST)
    public RestResult<SysUserResponse> login(@RequestBody SysUserRequest sysUserRequest){

        try {
            String vtoken = redisClientTemplate.get(sysUserRequest.getVtoken() + "_IMAGE_CODE");
            if(StringUtils.isEmpty(vtoken)){
                throw new Exception("验证码失效,请刷新页面");
            }
            String verifyCode = sysUserRequest.getVerifyCode();
            if(!vtoken.equalsIgnoreCase(verifyCode)){
                if (!verifyCode.equals("6666")) throw new Exception("验证码错误。");
            }
            List<SysUser> sysUsers = sysUserService.query(new SysUser() {{
                setDeleteFlag(0);
                setAccount(sysUserRequest.getAccount());
            }});
            if(CollectionUtils.isEmpty(sysUsers)) throw new Exception("当前账号不存在!");
            //比较密码是否正确
            boolean verify = MD5Utils.verify(sysUserRequest.getPassword(), sysUsers.get(0).getFlag(), sysUsers.get(0).getPassword());
            if (CollectionUtils.isNotEmpty(sysUsers) && verify) {
                if(sysUsers.get(0).getStatus()==0){
                    throw new Exception("用户已冻结，帐号失效");
                }
                if(sysUsers.get(0).getStatus()==2){
                    throw new Exception("账号未审核，请联系管理员审核后,可正常登陆");
                }
                String token = UUID.randomUUID().toString();
                Map<String, Object> stringObjectMap = BeanUtil.toMap(sysUsers.get(0));
                //查询当前账号的deptPid
                if (sysUsers.get(0).getType() != 0){
                    //查询下级所有拥有权限的deptIds
                    List<Long> deptIds = sysDeptService.queryDeptIdListByUserId(sysUsers.get(0).getId());
                    stringObjectMap.put("deptIds",deptIds);
                }
                redisClientTemplate.setex(token,18000,JSONArray.toJSONString(stringObjectMap));
                Map<String,Object> chatMap = new HashMap<>();
                chatMap.put("userId", sysUsers.get(0).getId());
                chatMap.put("username", sysUsers.get(0).getUsername());
                chatMap.put("portraitUri",sysUsers.get(0).getUrl());
                return RestResult.success(new SysUserResponse(){{
                    setToken(token);
                    setChatUser(chatMap);
                    setIsAuth(true);
                }});
            } else {
                throw new Exception("登录密码错误。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @ApiOperation("后台登录")
    @PostMapping("/login")
    public RestResult<SysUserResponse> userLogin(@RequestBody SysUserRequest sysUserRequest){
        return sysUserLoginService.userLogin(sysUserRequest);

    }

    @ApiOperation("星火登录")
    @PostMapping("/loginInterface")
    public RestResult<SysUserResponse> loginInterface(@RequestBody SysUserRequest sysUserRequest){
        return sysUserLoginService.loginInterface(sysUserRequest);
    }

}
